package com.imflea.zero.utils;

import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.util.ZeroJsonUtils;
import com.imflea.zero.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 祥保玉
 * @PackageName: com.imflea.zero.utils
 * @ClassName: WxAuthUtils
 * @Description
 * @date 2021-09-13  15:25:41
 */
public class WxAuthUtils {

    private static final Logger logger = LoggerFactory.getLogger(WxAuthUtils.class);

    public static Map<String, String> getOpenId(String code, String wxAppId, String wxSecret) throws Exception {
        // 授权（必填）
        String grant_type = "authorization_code";
        //通过后端前端传递的TenantId，进行获取  queryWxConfigInfoByTenantId
        //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        if (CommonUtils.isNull(code)) {
            throw new BizException("授权码为空");
        }
        if (CommonUtils.isNull(wxAppId)) {
            throw new BizException("微信小程序ID为空");
        }
        if (CommonUtils.isNull(wxSecret)) {
            throw new BizException("微信小程序密钥为空");
        }

        String params = "appid=" + wxAppId + "&secret=" + wxSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        String sr = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        Map<String, Object> responseMaps = ZeroJsonUtils.jsonToMap(sr);
        String message = (String) responseMaps.get("errmsg");
        if (!CommonUtils.isNull(message)) {
            throw new BizException("微信登录失败：" + message);
        }

        logger.error("数据对象：" + responseMaps);
        String openId = (String) responseMaps.get("openid");
        String unionId = (String) responseMaps.get("unionid");
        String sessionKey = (String) responseMaps.get("session_key");

        Map<String, String> result = new HashMap<>();
        result.put("openId", openId);
        result.put("unionId", unionId);
        result.put("sessionKey", sessionKey);
        return result;
    }

    public static String getSessionKey(String code, String wxAppId, String wxSecret) throws Exception {
        // 授权（必填）
        String grant_type = "authorization_code";
        //通过后端前端传递的TenantId，进行获取  queryWxConfigInfoByTenantId
        //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        if (CommonUtils.isNull(code)) {
            throw new BizException("授权码为空");
        }
        if (CommonUtils.isNull(wxAppId)) {
            throw new BizException("微信小程序ID为空");
        }
        if (CommonUtils.isNull(wxSecret)) {
            throw new BizException("微信小程序密钥为空");
        }

        String params = "appid=" + wxAppId + "&secret=" + wxSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        String sr = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        Map<String, Object> responseMaps = ZeroJsonUtils.jsonToMap(sr);
        String message = (String) responseMaps.get("errmsg");
        if (!CommonUtils.isNull(message)) {
            throw new BizException("微信登录失败：" + message);
        }

        logger.error("数据对象：" + responseMaps);
        String openId = (String) responseMaps.get("openid");
        String unionId = (String) responseMaps.get("unionid");
        String sessionKey = (String) responseMaps.get("session_key");

        Map<String, String> result = new HashMap<>();
        result.put("openId", openId);
        result.put("unionId", unionId);
        result.put("sessionKey", sessionKey);
        return sessionKey;
    }

    public static Map<String, Object> getUserDetailInfo(String wxAppid, String wxSecret, String openId, String encryptedData, String sessionKey, String iv) throws Exception {
        // 1、对encryptedData加密数据进行AES解密
        String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
        logger.error("解密后的数据对象：" + result);
        if (!CommonUtils.isNull(result)) {
            Map<String, Object> userInfoJSON = ZeroJsonUtils.jsonToMap(result);
            logger.error("格式转换后的数据对象：" + userInfoJSON);
            return userInfoJSON;
        } else {
            throw new BizException("信息解析错误");
        }
    }

    public static String getAccessToken(String wxAppId, String wxSecret) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppId + "&secret=" + wxSecret;
        String tokenInfo = HttpUtil.sendGet(url, null);
        // 转成Json对象 获取openid
        Map<String, String> map = new HashMap<String, String>();
        //转化成json
        Map<String, Object> fromObject = ZeroJsonUtils.jsonToMap(tokenInfo);
        //获取at
        String accessToken = (String) fromObject.get("access_token");
        return accessToken;
    }

    public static String sendMessage(String touser, String templateId, Map<String, Object> data, String state, String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

        data.put("touser", touser);
        data.put("template_id", templateId);
        data.put("miniprogram_state", state);
        String datas = ZeroJsonUtils.mapToJson(data);

        String result = HttpUtil.sendPost(url, datas);
        System.out.println(result);

        return result;
    }

    public static void main(String[] args) throws Exception {
        String token = getAccessToken("wx959230202e08bc7b", "e8cd6510c98d684f848c7297253e2a76");

        Map<String, Object> data = new HashMap<>();
        data.put("page", "/pages/welcome/index");
        Map<String, Object> mapData = new HashMap<>();

        mapData.put("lang", "zh_CN");

        Map<String, Object> v1 = new HashMap<>();
        v1.put("value", "苏长杰1号-帅气-潇洒2022款");
        mapData.put("thing1", v1);


        Map<String, Object> v2 = new HashMap<>();
        v2.put("value", "AD8889893997");
        mapData.put("character_string2", v2);


        Map<String, Object> v3 = new HashMap<>();

        v3.put("value", "2022-04-09 12:10:10");
        mapData.put("date3", v3);


        Map<String, Object> v4 = new HashMap<>();
        v4.put("value", "圆通快递");
        mapData.put("thing4", v4);


        Map<String, Object> v5 = new HashMap<>();

        v5.put("value", "123456789");
        mapData.put("character_string5", v5);


        Map<String, Object> mapData2 = new HashMap<>();
        Map<String, Object> p3 = new HashMap<>();
        p3.put("value", "待收获");
        mapData2.put("phrase3", p3);

        Map<String, Object> p4 = new HashMap<>();
        p4.put("value", "认养");
        mapData2.put("phrase2", p4);

        Map<String, Object> p5 = new HashMap<>();
        p5.put("value", "编号22038997的小可爱可以收获啦");
        mapData2.put("thing8", p5);


        data.put("data", mapData2);
        for (int i = 0; i < 100; i++) {

        }


//        sendMessage("o_zfq5MvceejZSd0Tk-QtmdNXuI8", "nqGW3RK39HesdLNv_Va4ky1GtZVHUXoElApjL1ebsJU", data, "developer", token);
        sendMessage("o_zfq5MvceejZSd0Tk-QtmdNXuI8", "MjkhLmzB4-VM2Y729sjEtQvIsTOXmiawe0LcR-lR2AA", data, "developer", token);

//        sendMessage("o_zfq5GGH-mmeRnCfclidcj0AHCY", "nqGW3RK39HesdLNv_Va4ky1GtZVHUXoElApjL1ebsJU", mapData, "developer", token);
    }
}
